package com.example.order.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author : zhayh
 * @date : 2021-5-8 19:49
 * @description : 订单队列服务类
 */
@Slf4j
@Service
public class OrderQueueService {
    @Resource
    private RabbitTemplate rabbitTemplate;

    // 下单成功后，向队列1放入订单消息
    public boolean sendCreateMessage(String orderCode) {
        try {
            rabbitTemplate.convertAndSend("exchange.order", "confirm", orderCode);
            log.info("向队列1：商家确认队列推送订单： {}", orderCode);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 店铺制作完成后，向队列2放入订单消息
    public boolean sendOrderDeliverMessage(String orderCode) {
        try {
            rabbitTemplate.convertAndSend("exchange.order", "deliver", orderCode);
            log.info("向队列2：待配送队列推送订单： {}", orderCode);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 骑手配送完成后或商家配送完成后，向队列4放入订单消息
    public boolean sendCompleteMessage(String orderCode) {
        try {
            rabbitTemplate.convertAndSend("exchange.order", "complete", orderCode);
            log.info("向队列4：配送完成队列推送订单： {}", orderCode);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 手动从队列2中出队一条待配送订单用于骑手配送
    public String receiveDeliverOrder() {
        Message msg = rabbitTemplate.receive("queue.order.deliver");
        if (msg != null) {
            try {
                String orderCode = new String(msg.getBody(), StandardCharsets.UTF_8);
                log.info("从队列2：待配送队列获取订单： {}", orderCode);
                return orderCode;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        log.info("队列2中无待配送订单");
        return null;
    }
}
